package com.gepengjun.lims.config.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.gepengjun.lims.util.JsonResult.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ShiroPermFilter extends PermissionsAuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        System.out.println("ShiroPermFilter----+isAccessAllowed");
        Subject subject = getSubject(request, response);
        String[] perms = (String[]) mappedValue;

        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else {
                if (!subject.isPermittedAll(perms)) {
                    isPermitted = false;
                }
            }
        }
        System.out.println("isPermitted-------"+isPermitted);
        return isPermitted;
    }

    @Override
    public boolean onAccessDenied(ServletRequest req, ServletResponse res) throws IOException {
        System.out.println("ShiroPermFilter--onAccessDenied-");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String requestedWith = request.getHeader("X-Requested-With");
        System.out.println("onAccessDenied--requestedWith-"+requestedWith);
        if (StringUtils.isNotEmpty(requestedWith) && StringUtils.equals("XMLHttpRequest",requestedWith)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(JSON.toJSONString(ResultUtil.error(403,"无权限-无指定权限 ")));
        }else {
            System.out.println("onAccessDenied--403-");
            response.sendRedirect("/unautho");
        }
        return false;
    }
}
